<template>
  <el-main>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbNameP }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      :inline="true"
      :model="formInline"
      class="el-form query-form el-form--label-right el-form--inline"
    >
      <el-form-item label="名称">
        <el-input
          size="small"
          v-model="formInline.search"
          placeholder="请输入"
        ></el-input>
      </el-form-item>

      <el-form-item label="日期">
        <el-date-picker
          v-model="formInlineD.dataValue"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="-"
          format="yyyy - MM - dd "
          value-format="yyyy-MM-dd"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="changeDatePicker"
        >
          <!-- :picker-options="pickerOptions" -->
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          @click="onSearch"
          icon="el-icon-search"
          >查 询</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="handleShow"
          icon="el-icon-plus"
          >添 加</el-button
        >
        <!-- <el-button size="small" type="primary" @click="uploadDialogVisible = true"
          icon="el-icon-upload2">导入运单</el-button> -->
        <!-- 
        <el-button size="small" type="primary" icon="el-icon-download">
          <a style="color: #fff;text-decoration: none;" @click="exportReport($event)" href=""
            download="运单导入模板.xlsx">下载模板</a>
        </el-button> -->
        <!-- <el-button size="small" type="primary" @click="onCheck" v-show="is_check" icon="el-icon-upload">批量发布</el-button> -->
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      style="margin-top: 30px"
      reserve-selection="true"
      ref="multipleTable"
      row-key="id"
      :tree-props="{ children: 'childs' }"
      :indent="30"
    >
      <!-- <el-table-column type="selection" width="50" fixed="left" :selectable="selectable"></el-table-column> -->
      <el-table-column label="序号" width="80">
        <template slot-scope="scope">
          <!-- 判断当前行是否有父级，如果没有，则显示当前页的序号，如果有，则显示子级序号 -->
          {{ scope.row.parentId == "0" ? scope.$index + 1 : "" }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="200"></el-table-column>
      <!-- <el-table-column prop="type" label="分类"></el-table-column> -->
      <el-table-column
        prop="createtime"
        label="创建时间"
        width="100"
      ></el-table-column>
      <el-table-column prop="coverImg" width="300" label="封面图">
        <template slot-scope="scope">
          <div style="display: flex">
            <div
              v-for="(item, index) in getArrLust(scope.row.coverImg)"
              :key="index"
              style="padding-right: 10px"
            >
              <img
                :src="item != '' ? common.getUrl(item) : ''"
                min-width="70"
                height="70"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="讲解链接"> </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>
      <el-table-column prop="content" label="详细内容" width="300">
        <template slot-scope="scope">
          <!-- <el-tooltip :content="scope.row.content" placement="top" class="custom-width"> -->
          <div class="ellipsis-2-lines">{{ scope.row.content }}</div>
          <!-- </el-tooltip> -->
        </template>
      </el-table-column>

      <el-table-column label="操作" :width="400" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.parentId == '0'"
            @click="handleShow(scope.$index, scope.row)"
            >添加</el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="handleDelete(scope.$index, scope.row, 0)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.status == 1"
            @click="handleDelete(scope.$index, scope.row, 1)"
            >开启</el-button
          >
          <el-button
            size="mini"
            type="default"
            v-if="scope.row.status == 0"
            @click="handleDelete(scope.$index, scope.row, 2)"
            >禁用</el-button
          >

          <el-button
            size="mini"
            type="default"
            @click="handleDetail(scope.$index, scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="formInline.page"
      :page-size="formInline.limit"
      :hide-on-single-page="true"
      layout="total, prev, pager, next"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="addDialogVisible"
      width="40%"
      center
      :before-close="beforeClose"
      custom-class="center_dislog"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        label-width="130px"
        :rules="addRules"
      >
        <div class="title_import_title"></div>

        <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <!-- <el-form-item label="类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择" filterable>
            <el-option
              v-for="(item, index) in truckType"
              :key="index"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="内容" prop="content">
          <el-input v-model="addForm.content" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="讲解链接" prop="type">
          <el-input v-model="addForm.url" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="type">
          <el-input v-model="addForm.address" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <el-upload
            class="upload-demo"
            action="/api/upload"
            :headers="headers"
            :multiple="true"
            :limit="2"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            accept="image/*"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip">只能上传图,最多上传2张</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="addSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-main>
</template>
<script>
import { mapState } from "vuex";
import {
  waybillEdit,
  waybillPush,
  uploadNew,
  crateMuseum,
  getMuseumPageList,
  delMuseum,
} from "../../api.js";
export default {
  name: "mangeShowList",
  data() {
    return {
      fileList: [], // 用于存储上传的文件列表
      headers: {},
      imageArr: [],
      switchTab: true,
      switchselectValue: "启用",
      isAdd: true,
      isDisabled: false,
      addDialogVisible: false,
      addDisabled: false,
      is_check: false,
      breadcrumbName: "",
      breadcrumbPath: "",
      breadcrumbNameP: "",
      tableData: [],
      //查询栏默认展示数据
      formInlineD: {
        dataValue: [],
        value: "",
      },
      formInline: {
        search: "",
        starttime: "",
        endtime: "",
        page: 1,
        limit: 5,
        type: 0,
      },
      addForm: {
        address: "",
        title: "",
        type: 0,
        createpersonid: "00001",
        createname: "管理员",
        content: "",
        coverImg: "",
        status: 0,
        url: "",
      },
      indexId: "",
      //分页
      total: 0,
      TimeType: [],
      needData: [],
      truckType: [
        { name: "展厅展览", id: 0 },
        { name: "馆藏文物", id: 1 },
      ],
      dialogTitle: "",
      updateFrom: {
        transport_sn: "",
        transport_snArr: "",
      },
      addRules: {
        transport_sn: [
          {
            required: true,
            message: "请输入运单号",
            trigger: "blur",
          },
        ],
        truck_type: [
          {
            required: true,
            message: "请选择车辆类型",
            trigger: "blur",
          },
        ],
        publish_phone: [
          {
            required: true,
            message: "请输入发布人联系电话",
            trigger: "blur",
          },
        ],
        delivery_time: [
          {
            required: true,
            message: "请选择日期",
            trigger: "blur",
          },
        ],
        transport_total_amt: [
          {
            required: true,
            message: "请输入价格",
            trigger: "blur",
          },
        ],
        transport_weight: [
          {
            required: true,
            message: "请输入载重量",
            trigger: "blur",
          },
        ],
        delivery_need: [
          {
            required: true,
            message: "配送配置",
            trigger: "change",
          },
        ],
        nucleic_acid: [
          {
            required: true,
            message: "请选择核酸",
            trigger: "blur",
          },
        ],
        green_code: [
          {
            required: true,
            message: "请选择行程码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  async mounted() {
    this.breadcrumbName = this.$route.query.breadcrumbName;
    this.breadcrumbPath = this.$route.query.breadcrumbPath;
    this.breadcrumbNameP = this.$route.query.breadcrumbNameP;
    var date = new Date();
    var Simdate = this.DateTime(date.getTime() + 24 * 60 * 60 * 1000);
    // this.updateFrom.DeliveryDt = Simdate;
    this.formInlineD.value = Simdate;
    // 暂时注册
    this.getMuseumPageListList(this.formInline);
  },
  methods: {
    getIndex(index) {
      // 根据需要自定义序号，这里简单返回 index + 1 作为序号
      return index + 1;
    },
    getMuseumPageListList(searchObj) {
      getMuseumPageList(searchObj).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
          console.log(res.data);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 上传成功回调
    handleUploadSuccess(response, file) {
      this.imageArr.push(response.data);
      console.log("上传成功:", this.imageArr);
    },
    // 上传失败回调
    handleUploadError(err) {
      this.$message.error("文件上传失败，请稍后重试");
    },
    // 删除文件回调
    handleRemove(file, fileList) {
      this.imageArr = [];
      fileList.map((item) => {
        this.imageArr.push(item.response.data);
      });
    },
    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/"); // 校验是否为图片
      const isSizeValid = file.size / 1024 / 1024 < 5; // 校验图片大小，限制为 5MB

      if (!isImage) {
        this.$message.error("只能上传图片格式");
        return false;
      }
      if (!isSizeValid) {
        this.$message.error("图片大小不能超过 5MB");
        return false;
      }
      return true;
    },

    changeSwitch(val) {
      console.log("val", val);
      if (val) {
        this.switchselectValue = "启用";
      } else {
        this.switchselectValue = "关闭";
      }
    },
    //编辑
    handleEdit(index, row) {
      this.isAdd = false;
      this.dialogTitle = "编辑";
      this.addForm.id = row.id;
      this.addForm.title = row.title;
      this.addForm.type = row.type;
      this.addForm.content = row.content;
      this.addForm.coverImg = row.coverImg;
      this.addForm.url = row.url;
      this.addForm.address = row.address;
      if (row.coverImg != "") {
        this.imageArr = row.coverImg.split(",");
        this.fileList = row.coverImg.split(",").map((item, index) => ({
          name: index,
          url: this.common.getUrl(item),
          status: "success",
        }));
      }
      console.log(this.fileList, " this.fileList");
      this.addDialogVisible = true;
    },
    //表格分页
    handleCurrentChange(val) {
      this.formInline.page = val;
      this.getMuseumPageListList(this.formInline);
    },
    //表格查询
    onSearch() {
      this.formInline.page = 1;
      this.getMuseumPageListList(this.formInline);
    },
    handleShow(index, row) {
      this.isAdd = true;
      this.dialogTitle = "添加";
      this.addDialogVisible = true;
      if (row.id) {
        this.indexId = row.id;
      }
    },

    //查看
    handleDetail(index, row) {
      this.$router.push({
        path: "/mange/way_detail",
        query: {
          id: row.id,
          state: 0,
        },
      });
    },

    //刪除
    handleDelete(index, row, type) {
      var _this = this;
      var title =
        type == 0
          ? "是否确认刪除该数据？"
          : type == 1
          ? "是否确认启用该数据？"
          : "是否确认禁用该数据？";
      _this
        .$confirm(title, "提 示", {
          confirmButtonText: "确 定",
          cancelButtonText: "取 消",
          center: true,
        })
        .then(() => {
          var data = {
            Id: row.id,
            type: type,
          };
          delMuseum(data).then((res) => {
            if (res.code == 200) {
              _this.getMuseumPageListList(_this.formInline);
              let msg =
                type == 0 ? "删除成功" : type == 1 ? "已启用" : "已禁用";
              _this.$message.success(msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },

    //提交
    addSubmit() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          var _this = this;
          _this.addForm.parentId = this.indexId == "" ? 0 : this.indexId;
          _this.addForm.coverImg = this.imageArr.join(",");
          var dataObj = JSON.parse(JSON.stringify(_this.addForm));
          if (_this.isAdd) {
            crateMuseum(dataObj).then((res) => {
              console.log(res);
              if (res.code == 200) {
                _this.addDialogVisible = false;
                _this.$refs.addForm.resetFields();
                _this.getMuseumPageListList(_this.formInline);
                _this.beforeClose();

                _this.isDisabled = false;
                _this.$message.success("添加成功");
              } else {
                _this.isDisabled = false;
                this.$message.error(res.msg);
              }
            });
          } else {
            var dataObj = JSON.parse(JSON.stringify(_this.addForm));
            crateMuseum(dataObj).then((res) => {
              if (res.code == 200) {
                _this.$message.success("编辑成功");
                _this.$refs.addForm.resetFields();
                _this.beforeClose();
                _this.getMuseumPageListList(_this.formInline);
                _this.isDisabled = false;
                _this.addDialogVisible = false;
              } else {
                _this.isDisabled = false;
                this.$message.error(res.ErrorMsg);
              }
            });
          }
        }
      });
    },
    selectable(row, index) {
      return row.ship_state == 0;
    },
    //发布
    handlePush(index, row) {
      this.updateFrom.transport_sn = row.transport_sn;
      this.typeSn = 1;
      this.addSubmitPush();
    },
    onCheck() {
      this.typeSn = 2;
      this.addSubmitPush();
    },
    //发布
    addSubmitPush() {
      var _this = this;
      _this.isDisabled = true;
      var data = {
        ship_state: 1,
      };
      if (this.typeSn == 1) {
        data.transport_sn = _this.updateFrom.transport_sn;
      } else {
        data.transport_sn = _this.updateFrom.transport_snArr;
      }
      waybillPush(data).then((res) => {
        if (res.ErrorCode == 0) {
          _this.addDialogVisible = false;
          _this.getMuseumPageListList(_this.formInline);
          _this.isDisabled = false;
          _this.$message.success("发布成功");
        } else {
          _this.isDisabled = false;
          this.$message.error(res.ErrorMsg);
        }
      });
    },
    removeDomain(item) {
      var index = this.editForm.domains.indexOf(item);
      if (index !== -1) {
        this.editForm.domains.splice(index, 1);
      }
    },
    addDomain() {
      this.editForm.domains.push({
        customer_name: "",
        customer_addr: "",
        customer_sn: "",
        // key: Date.now()
      });
    },
    beforeClose() {
      this.addDialogVisible = false;
      this.$refs.addForm.resetFields();
      this.addForm = {
        title: "",
        type: 0,
        content: "",
        coverImg: "",
        status: 0,
        url: "",
        address: "",
      };
      this.fileList = [];
    },
    formatNorm(row, column, cellValue) {
      return row.loadRangeMin + "~" + row.loadRangeMax;
    },

    changeDatePicker(val) {
      if (val) {
        this.formInline.starttime = val[0];
        this.formInline.endtime = val[1];
      } else {
        this.formInline.starttime = "";
        this.formInline.endtime = "";
      }
    },

    DateTime(time) {
      var oDate = new Date(time),
        oYear = oDate.getFullYear(),
        oMonth = oDate.getMonth() + 1,
        oDay = oDate.getDate(),
        oTime = oYear + "-" + this.getzf(oMonth) + "-" + this.getzf(oDay);
      return oTime;
    },
    getzf(num) {
      if (parseInt(num) < 10) {
        num = "0" + num;
      }
      return num;
    },
    formatDept(row, column, cellValue) {
      return Array.prototype.join.call(cellValue, "，");
    },
    getArrLust(img) {
      var list = img.split(",");
      return list;
      // console.log("imgimgimgimgimgimg", img, list);
    },
    formatPassCheck(cellValue) {
      if (cellValue == 0) {
        return "已发布";
      } else if (cellValue == 1) {
        return "禁用中";
      }
    },
    // handleSelectionChange(selection) {
    //     if (selection.length == 0) {
    //         this.is_check = false
    //         this.updateFrom.transport_snArr = ""
    //     } else {
    //         this.updateFrom.transport_snArr = ""
    //         var UnifiedTimesNoArr = [];
    //         for (var i in selection) {
    //             UnifiedTimesNoArr.push(selection[i].transport_sn)
    //             this.updateFrom.transport_snArr = UnifiedTimesNoArr.join(',')
    //         }
    //         this.is_check = true
    //     }
    // },
    // //下载模板
    // exportReport(e) {
    //     e.target.href = this.baseUrl + 'report/export/shipment_download_xlsx?code=shipment' +
    //         '&access_token=' + this.Token
    // },
  },
  computed: {
    ...mapState({
      baseUrl: (state) => state.baseUrl,
      Token: (state) => state.access_token,
    }),
  },
};
</script>

<style scoped>
.title_import_title {
  padding: 0 20px;
  padding-bottom: 30px;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.custom-width .el-tooltip__popper {
  max-width: 200px !important;
  /* 设置最大宽度 */
}

.el-dialog__header {
  text-align: center;
}

.el-dialog__footer {
  text-align: center !important;
}

.img-table {
  width: 50px;
  height: 50px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.ellipsis-2-lines {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: 3em;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
